package com.charley.icloud.admin.webapps.sysuser.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.charley.icloud.admin.common.constant.SysTableConstants;
import com.charley.icloud.admin.utils.RandomAccountGenerator;
import com.charley.icloud.admin.webapps.sysuser.pojo.entity.SysUserDO;
import com.charley.icloud.admin.webapps.sysuser.pojo.request.SysUserQuery;
import com.charley.icloud.admin.webapps.sysuser.pojo.model.SysUserVO;
import com.charley.icloud.admin.webapps.sysuser.service.SysUserService;
import com.charley.icloud.common.constants.SystemNumberConstants;
import com.charley.icloud.common.response.code.BackAdminSysCode;
import com.charley.icloud.common.response.result.HttpResponseResult;
import com.charley.icloud.common.response.result.HttpResponseResultFactory;
import com.charley.icloud.common.utils.FileUtils;
import com.charley.icloud.datasource.page.PageRequest;
import com.charley.icloud.security.utils.PasswordUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 该接口是超级管理员独有
 * 可由超管在后台进行用户注册和用户管理(CRUD)
 */
@Slf4j
@RestController
@Tag(name = "用户控制器")
@RequestMapping(value = "/sys/user")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    @PostMapping(value = "/save")
    @Operation(summary = "保存用户", description = "后台管理系统")
    public HttpResponseResult save(@RequestBody SysUserQuery query) {
        // TODO: 后续在添加日志模块时，使用AOP进行参数校验
        if (ObjectUtils.isEmpty(query)) {
            log.error("System User registerNewUser SysUserQuery is null");
            HttpResponseResult httpResponseResult = HttpResponseResultFactory.fail(BackAdminSysCode.SYSTEM_USER_ERROR_ADD_FAIL_PARAM_NULL, BackAdminSysCode.SYSTEM_USER_ERROR_ADD_FAIL_PARAM_NULL_MSG);
            log.info("system user addUser return msg: {}", httpResponseResult);
            return httpResponseResult;
        }
        Date nowDate = new Date();
        SysUserDO user = sysUserService.findById(query.getId());
        if (user != null && user.getId() != null) {
            if (SysTableConstants.SYS_USER_TABLE_TYPE_SUPER_ADMIN.equals(user.getType())) {
                HttpResponseResult httpResponseResult = HttpResponseResultFactory.fail("超级管理员不允许修改!");
                log.error("System User registerNewUser SysUserQuery is Exception: {}", httpResponseResult);
                return httpResponseResult;
            }
            // 将修改内容COPY到user中
            BeanUtil.copyProperties(query, user, CopyOptions.create().ignoreCase().ignoreNullValue());
            user.setLastUpdateBy("System");
            user.setLastUpdateTime(nowDate);
        }
        if (StringUtils.isNotBlank(query.getPassword())) {
            String salt = PasswordUtils.getSalt();
            if (user == null) {
                // 新增用户
                user = new SysUserDO();
                BeanUtil.copyProperties(query, user, CopyOptions.create().ignoreCase().ignoreNullValue());
                String password = PasswordUtils.encode(query.getPassword(), salt);
                user.setSalt(salt);
                user.setPassword(password);
                user.setLastChangePwdTime(nowDate);

                // 完善数据
                // 生成9位的随机账号
                while (true) {
                    String account = RandomAccountGenerator.getAccountByUUID();
                    Boolean existed = sysUserService.existUserByAccount(account);
                    if (!existed) {
                        user.setAccount(account);
                        break;
                    }
                }
                user.setCreateBy("System");
                user.setCreateTime(nowDate);
            } else {
                // 修改用户且修改了密码
                if (StringUtils.isNotBlank(query.getPassword())) {
                    String password = PasswordUtils.encode(query.getPassword(), salt);
                    user.setSalt(salt);
                    user.setPassword(password);
                    user.setLastChangePwdTime(nowDate);
                }
            }
        }
        assert user != null;
        user.setLastUpdateBy("System");
        user.setLastUpdateTime(nowDate);
        if (sysUserService.save(user) > SystemNumberConstants.SYSTEM_NUMBER_INTEGER_ZERO) {
            SysUserVO userInfoRet = new SysUserVO();
            BeanUtil.copyProperties(user, userInfoRet, CopyOptions.create().ignoreCase().ignoreNullValue());
            return HttpResponseResultFactory.buildHttpResponseResult(BackAdminSysCode.SYSTEM_USER_SUCCESS_SAVE, BackAdminSysCode.SYSTEM_USER_SUCCESS_SAVE_MSG, userInfoRet);
        } else {
            return HttpResponseResultFactory.fail(BackAdminSysCode.SYSTEM_USER_ERROR_SAVE_FAIL, BackAdminSysCode.SYSTEM_USER_ERROR_SAVE_FAIL_MSG);
        }
    }

    @PostMapping(value = "/delete")
    @Operation(summary = "删除用户", description = "后台管理系统")
    public HttpResponseResult delete(@RequestBody List<SysUserQuery> queries) {
        List<SysUserDO> records = new ArrayList<>();
        if (queries != null && queries.size() > SystemNumberConstants.SYSTEM_NUMBER_INTEGER_ZERO) {
            for (SysUserQuery query : queries) {
                // 根据用户ID获取用户信息
                SysUserDO sysUser = sysUserService.findById(query.getId());
                if (sysUser != null && SysTableConstants.SYS_USER_TABLE_TYPE_SUPER_ADMIN.equals(sysUser.getType())) {
                    return HttpResponseResultFactory.fail("超级管理员不允许删除!");
                }
                SysUserDO record = new SysUserDO();
                BeanUtil.copyProperties(query, record, CopyOptions.create().ignoreCase().ignoreNullValue());
                records.add(record);
            }
        }
        return HttpResponseResultFactory.success(sysUserService.delete(records));
    }

    @PostMapping(value = "/findPage")
    @Operation(summary = "分页列表查询", description = "后台管理系统")
    public HttpResponseResult findPage(@RequestBody PageRequest pageRequest) {
        return HttpResponseResultFactory.success(sysUserService.findPage(pageRequest));
    }

    @GetMapping(value = "/findByAccount")
    @Operation(summary = "根据账号查询用户信息", description = "后台管理系统")
    @Parameter(name = "account", description = "用户账号", required = true, in = ParameterIn.QUERY)
    public HttpResponseResult findByAccount(@RequestParam String account) {
        return HttpResponseResultFactory.success(sysUserService.findByAccount(account));
    }

    @GetMapping(value = "/findByID")
    @Operation(summary = "根据账号ID查询用户信息", description = "后台管理系统")
    @Parameter(name = "userId", description = "用户ID", required = true, in = ParameterIn.QUERY)
    public HttpResponseResult findByUserID(@RequestParam String userId) {
        if (StringUtils.isBlank(userId) || !StringUtils.isNumeric(userId)) {
            return HttpResponseResultFactory.fail("参数格式非空或包含其数字字符，请检查后重试");
        }
        return HttpResponseResultFactory.success(sysUserService.findById(Long.parseLong(userId)));
    }

    @PostMapping(value = "/exportExcelUser")
    @Operation(summary = "导出用户信息Excel表", description = "后台管理系统")
    public void exportExcelUser(@RequestBody PageRequest pageRequest, HttpServletResponse res) {
        File file = sysUserService.createUserExcelFile(pageRequest);
        FileUtils.downloadFile(res, file, file.getName());
    }

}
